import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '用户登录', hideInMenu: true }
  },
  {
    path: '/trains',
    name: 'TrainManagement',
    component: () => import('@/views/train/TrainManagement.vue'),
    meta: { title: '车次管理', requiresAuth: true, adminOnly: true }
  },
  {
    path: '/stations',
    name: 'StationManagement', 
    component: () => import('@/views/train/StationManagement.vue'),
    meta: { title: '车站管理', requiresAuth: true, adminOnly: true }
  },
  {
    path: '/carriages',
    name: 'CarriageManagement',
    component: () => import('@/views/seat/CarriageManagement.vue'),
    meta: { title: '车厢管理', requiresAuth: true, adminOnly: true }
  },
  {
    path: '/ticket-management',
    name: 'TicketManagement',
    component: () => import('@/views/ticket/TicketManagement.vue'),
    meta: { title: '票务管理', requiresAuth: true, adminOnly: true }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: () => import('@/views/user/UserManagement.vue'),
    meta: { title: '用户管理', requiresAuth: true, adminOnly: true }
  },
  {
    path: '/purchase',
    name: 'TicketPurchase',
    component: () => import('@/views/ticket/TicketPurchase.vue'),
    meta: { title: '购票系统', requiresAuth: true }
  },
  {
    path: '/orders',
    name: 'OrderManagement',
    component: () => import('@/views/ticket/OrderManagement.vue'),
    meta: { title: '订单管理', requiresAuth: true }
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: () => import('@/views/statistics/Statistics.vue'),
    meta: { title: '系统统计', requiresAuth: true, adminOnly: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 动态导入用户store避免循环依赖
  const { useUserStore } = await import('@/stores/user')
  const userStore = useUserStore()
  
  // 恢复用户登录状态
  if (!userStore.isLoggedIn) {
    userStore.restoreUser()
  }
  
  // 如果访问登录页面且已登录，重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next(userStore.isAdmin() ? '/trains' : '/purchase')
    return
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
    return
  }
  
  // 检查是否需要管理员权限
  if (to.meta.adminOnly && !userStore.isAdmin()) {
    next('/purchase') // 普通用户重定向到购票页面
    return
  }
  
  next()
})

export default router